package com.corner.web.controller.task;

import com.alibaba.fastjson2.JSON;
import com.corner.system.mqtt.MqttAcceptClient;
import com.corner.system.mqtt.MqttSendClient;
import com.corner.system.domain.MqttReq;
import com.corner.system.mapper.SysJxCommonDataMapper;
import com.corner.system.service.JxMqttService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @program: ruoyi
 * @description: 鸡西数据传输定时任务
 * @author: lydms
 * @create: 2024-04-07 11:21
 **/
@Slf4j
@Component
@EnableScheduling
public class jxTask {

    @Autowired
    ThreadPoolTaskExecutor executor;
    @Autowired
    private MqttSendClient mqttSendClient;
    @Autowired
    private JxMqttService jxMqttService;
    @Autowired
    private SysJxCommonDataMapper commonDataMapper;
    @Autowired
    private MqttAcceptClient mqttAcceptClient;

    @Value("${mqtt.defaultTopic}")
    private String defaultTopic;

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        scheduler.initialize();
        return scheduler;
    }


    @Scheduled(cron = "0 0/1 * * * ?")
    public void scheduled1(){
        List<Long> stationIds = commonDataMapper.selectStationIds();

        Thread thread = Thread.currentThread();
        String threadName = thread.getName();
        System.out.println("时间" + new Date()+",线程：" + threadName);
        for(Long id: stationIds){

            executor.execute(new Runnable() {
                @Override
                public void run() {
                    MqttReq mqttReq = null;
                    try {

                        mqttReq = jxMqttService.selectWswDataList(id);
                        if(mqttReq == null){
                            return;
                        }

                        String clientID = mqttReq.getClientID();
                        String topic = String.format(defaultTopic, clientID);
                        String mqttReqStr = JSON.toJSONString(mqttReq);
                        mqttSendClient.publish(false, topic, mqttReqStr);
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
//                    Map data = mqttReq.getData();
//                    String s = JSON.toJSONString(data);
//                    System.out.println(s);
                }
            });
        }

    }

    //@Scheduled(cron = "0/10 * * * * ?")
    public void checkConnected(){
        if (MqttAcceptClient.client == null || !MqttAcceptClient.client.isConnected()) {
            log.info("定时检查mqtt连接状态..."+System.currentTimeMillis());
            log.info("【连接状态为未连接，正在尝试重新连接】");
            mqttAcceptClient.connect();
        }
    }

    /*@Scheduled(cron = "* * * * * *")
    public void scheduled2(){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                log.info("=====>>>>>2222使用cron  {}",System.currentTimeMillis());
            }
        });

    }*/

    //@Scheduled(cron = "0 0/1 * * * ?")
    public void scheduledTest(){
        //List<Long> stationIds = commonDataMapper.selectStationIds();
        ArrayList<Long> stationIds = new ArrayList<>();
        stationIds.add(1l);
        stationIds.add(2l);
        stationIds.add(3l);
        stationIds.add(4l);
        Thread thread = Thread.currentThread();
        String threadName = thread.getName();
        System.out.println("时间" + new Date()+",线程：" + threadName);
        for(Long id: stationIds){

            executor.execute(new Runnable() {
                @Override
                public void run() {
                    MqttReq mqttReq = null;
                    try {

                        /*mqttReq = jxMqttService.selectWswDataList(id);
                        if(mqttReq == null){
                            return;
                        }

                        String clientID = mqttReq.getClientID();
                        String topic = String.format(defaultTopic, clientID);
                        String mqttReqStr = JSON.toJSONString(mqttReq);*/

                        String clientId = "KN20240001202404";
                        String topic = String.format(defaultTopic, clientId);
                        String mqttReqStr = "{aa:11}";
                        mqttSendClient.publish(false, topic, mqttReqStr);

                    }catch (Exception e){
                        e.printStackTrace();
                    }
//                    Map data = mqttReq.getData();
//                    String s = JSON.toJSONString(data);
//                    System.out.println(s);
                }
            });
        }

    }


}
